<template>
    <div>
        <el-card style="margin:20px 20px">
            <CategorySelect @getCategoryId='getCategoryId' :show="!isShowTable"/>
        </el-card>
        <el-card style="margin:20px 20px">
            <div v-show="isShowTable">
                <!-- disabled：没有category3Id时禁用此按钮 -->
                <el-button type="primary" icon="el-icon-plus" :disabled="!category3Id" @click="addAttr">添加属性
                </el-button>
                <!-- 表格：展示平台属性 -->
                <el-table :data="attrList" style="width: 100%" border>
                    <el-table-column type="index" label="序号" width="80" align='center'>
                    </el-table-column>
                    <el-table-column prop="attrName" label="属性名称" width="150">
                    </el-table-column>
                    <el-table-column prop="prop" label="属性值列表" width="width">
                        <template slot-scope="{row,$index}">
                            <el-tag type="success" v-for="(attrValue, index) in row.attrValueList">
                                {{ attrValue.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="prop" label="操作" width="150">
                        <template slot-scope="{row,$index}">
                            <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateAttr(row)">
                            </el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 添加属性或修改属性 -->
            <div v-show="!isShowTable">
                <el-form :inline="true" ref="form" label-width="80px" :model="attrInfo">
                    <el-form-item label="属性名">
                        <el-input placeholder="请输入属性名" v-model="attrInfo.attrName" @keyup.native.enter="addAttrValue">
                        </el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" icon="el-icon-plus" :disabled="!attrInfo.attrName" @click="addAttrValue">添加属性值
                </el-button>
                <el-button @click="isShowTable = true">取消</el-button>
                <el-table style="width: 100% ;margin: 20px 0px;" border :data="attrInfo.attrValueList">
                    <el-table-column type="index" label="序号" width="80" align='center'>
                    </el-table-column>
                    <el-table-column prop="prop" label="属性值名称" width="width">
                        <template slot-scope="{row,$index}">
                            <!-- 查看模式(span)与修改模式(input)间的切换 -->
                            <el-input v-model="row.valueName" placeholder="请输入属性值名称" v-if="row.flag" @blur="toLook(row)"
                                @keyup.native.enter="toLook(row)" :ref="$index"></el-input>
                            <span v-else @click="toEdit(row, $index)">
                                {{ row.valueName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="prop" label="操作" width="width">
                        <template slot-scope="{row,$index}">
                            <!-- 删除属性值按钮 -->
                            <!-- 此项目用的elementUI是2.13.2版本confirm要改成onConfirm -->
                            <el-popconfirm :title="`确定删除${row.valueName}吗？`" @onConfirm="deleteAttrValue($index)">
                                <el-button type="danger" icon="el-icon-delete" size="mini" slot="reference">
                                </el-button>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" @click="addOrUpdateAttr" :disabled="this.attrInfo.attrValueList.length<1">保存</el-button>
                <el-button @click="isShowTable = true">取消</el-button>
            </div>
        </el-card>
    </div>
</template>

<script>
//按需引入lodash当中的深拷贝
import cloneDeep from "lodash/cloneDeep";
export default {
    name: 'Attr',
    data() {
        return {
            category1Id: '',
            category2Id: '',
            category3Id: '',
            attrList: [],        //接受平台属性
            isShowTable: true,    //table显示与隐藏
            //收集新增属性|修改属性使用
            attrInfo: {
                attrName: "",        //属性名
                attrValueList: [],   //属性值（可以有多个，所以是数组，数组内对象需要有attrId,valueName）  
                categoryId: 0,       //三级分类的id
                categoryLevel: 3,    //区分几级分类id
            }
        };
    },
    mounted() {

    },
    methods: {
        //自定义事件的回调
        getCategoryId({ categoryId, level }) {
            if (level == 1) {
                this.category1Id = categoryId;
                this.category2Id = '';
                this.category3Id = '';
            }
            else if (level == 2) {
                this.category2Id = categoryId;
                this.category3Id = '';
            } else {
                this.category3Id = categoryId;
                //发请求获取平台属性
                this.getAttrList();
            }
        },
        //获取平台属性的数据方法
        async getAttrList() {
            const { category1Id, category2Id, category3Id } = this;
            let result = await this.$API.attr.reqAttrList(category1Id, category2Id, category3Id);
            if (result.code == 200) {
                this.attrList = result.data;
            }
        },
        //添加属性值回调
        addAttrValue() {
            //向属性值的数组里面添加元素
            this.attrInfo.attrValueList.push({
                attrId: this.attrInfo.id,  //对应的属性名的id,
                valueName: '',
                flag: true,              //用以切换查看模式和修改模式
            });
            //新添加的属性值自动聚焦
            this.$nextTick(() => {
                this.$refs[this.attrInfo.attrValueList.length - 1].focus();
            });

        },
        //添加属性回调
        addAttr() {
            //切换tab显示与隐藏
            this.isShowTable = false;
            //清空之前操作留下的的数据
            this.attrInfo = {
                attrName: "",
                attrValueList: [],
                categoryId: this.category3Id,   //收集到三级分类的id
                categoryLevel: 3,
            };
        },
        //修改某个属性
        updateAttr(row) {
            this.isShowTable = false;
            //将选中的属性赋值给attrInfo
            //深拷贝，拿到数据
            this.attrInfo = cloneDeep(row);
            //修改某个属性时，将相应的属性值元素加上flag这个标记
            this.attrInfo.attrValueList.forEach(item => {
                //flag不是响应式数据，要通过$set添加
                //第一个参数：对象，第二个参数：添加的新响应式属性第三个参数：新的属性的属性值
                this.$set(item, 'flag', false);
            })
        },
        //失去焦点的事件，修改模式切换成查看模式，展示span
        toLook(row) {
            //如果属性值为空不能作为新的属性值，提示用户
            if (row.valueName.trim() == '') {
                this.$message('属性值不能为空，请输入正常的属性值');
                return;
            }
            //新增的属性不能与已有的属性重复
            let isRepat = this.attrInfo.attrValueList.some(item => {
                if (row !== item) {
                    return row.valueName == item.valueName;
                };
            })
            if (isRepat) {
                this.$message('已有重复的属性值，请输入新的属性值');
                return;
            }
            row.flag = false;     //修改模式切换成查看模式
        },
        //点击span的回调
        toEdit(row, index) {
            row.flag = true;
            //点击span时，页面重绘（因为用v-if？）需要时间，不能立马获取到span
            //所以用$nextTick，（或定时器？）
            this.$nextTick(() => {
                //获得相应input表单元素实现聚焦
                this.$refs[index].focus();
            });
        },
        //点击确认删除对应属性值
        deleteAttrValue(index) {
            //删除对应属性值
            this.attrInfo.attrValueList.splice(index, 1);
        },
        //保存按钮：进行添加属性或修改属性的操作 
        async addOrUpdateAttr() {
            //整理参数：1、属性值为空的不应该提交给服务器
            //2、提交给服务器数据中不应该出现flag字段
            this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(item => {
                //过滤掉属性值不是空的
                if (item.valueName != '') {
                    //删除掉flag属性
                    delete item.flag;
                    return true;
                }
            })
            try {
                //发请求
               await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo);
                //显示平台属性的信号量进行切换
                this.isShowTable = true;
                this.$message({message: '保存成功',type: 'success'});
                //保存成功以后需要再次获取平台属性进行展示
                this.getAttrList();
            } catch (error) {
                this.$message.error('保存失败');
            }

        }
    },
};
</script>

<style lang="scss" scoped>

</style>